package com.yc.vote.mapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yc.vote.entity.Items;
import com.yc.vote.entity.Vote;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.*;

import javax.websocket.OnMessage;
import java.io.Serializable;
import java.util.List;

/**
 * <p>
 * 投票系统-题目表-2 Mapper 接口
 * </p>
 *
 * @author baomidou
 * @since 2024-04-14
 */
public interface VoteMapper extends BaseMapper<Vote> {

    @Select("select * from tp_vote where id=#{id}")
    @Results(
            id = "rm1",
            // 手工的字段映射 + 关联查询
            value = {
                    //映射主键字段 将数据库字段映射到实体类上 id=true 并且为主键字段
                    // id映射有特殊含义，与缓存有关，提升性能
                    @Result(column = "id", property = "id", id = true),
                    //一对多
                    @Result(column = "id", property = "items", many = @Many(select = "selectItemsByVid") ),
                    @Result(column = "id", property = "unum", one = @One(select = "countUnumByVid"))
            }
    )
    Vote selectById(Integer id);

    @Select("SELECT a.*, IFNULL(b.cnt, 0) AS unum \n" +
            "FROM tp_items a \n" +
            "LEFT JOIN (\n" +
            "    SELECT iid, COUNT(*) AS cnt \n" +
            "    FROM tp_record \n" +
            "    WHERE vid = #{vid} \n" +
            "    GROUP BY iid) b \n" +
            "ON a.id = b.iid\n" +
            "WHERE a.vid = #{vid}\n")
    List<Items> selectItemsByVid(Integer vid);


    @Select("select count(DISTINCT usid) unum,vid\n" +
            " from tp_record\n " +
            " where vid = #{vid} " +
            " group by vid ")
    int countUnumByVid(Integer vid);


    //concat 连接函数，将多个字符串连在一起变成一个字符串
    //#{}: 解析为SQL时，会将形参变量的值取出，并自动给其添加引号。
    // 例如：当实参username="Amy"时，sql会解析为 username="Amy"
    //但是使用${}，sql会解析为 username=Amy,不会自动添加引号
    @Select("<script> " +
            "select * from tp_vote " +
            "<where>" +
            " status = 1 " +
            "<if test='vname!=null'> and vname like concat('%',#{vname},'%') </if> " +
            "<if test=\"usid!=null and usid!=''\"> and usid = #{usid} </if> " +
            "</where> " +
            "</script>")
    //调用上面的@Results
    @ResultMap("rm1")
    //因为在语句使用了 #{vname}，所以加 @Param注解
    List<Vote> selectLikeVname(@Param("vname") String vname,@Param("usid") Integer usid);

}
